package com.lp.mgt.services.impls;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.lp.mgt.entities.Avatar;
import com.lp.mgt.mappers.FileMapper;
import com.lp.mgt.services.FileService;
import com.lp.mgt.utils.UUIDUtil;
@Service
public class FileServiceImpl implements FileService {
	@Autowired
	private FileMapper fileMapper;
	@Value("${localFilePath}")
	private String uploadPath;
	@Value("${showFilePath}")
	private String showPath;
	
	@Override
	public String[] avatarUpload(MultipartFile[] files,String username) {
		String[] ids=new String[files.length];
		if (files.length<1) {
			return null;
		}else {
			for(int i=0;i<files.length;i++) {
				MultipartFile file=files[i];
				if (file!=null) {
					String id=UUIDUtil.getUUID();
					String size=String.valueOf(file.getSize());
					String type=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
					//String path="D:\\入门到放弃/myWorkspace/ECLIPSE/MGT/user_avatar/"+username+type;
					String saveName=username+type;
					String path=uploadPath+saveName;
					File newFile = new File(path);
					//判断上传文件的保存目录是否存在
					if (!newFile.exists() && !newFile.isDirectory()) {
						System.out.println(path+"目录不存在，需要创建");
						//创建目录
						newFile.mkdir();
					}
					try {
						file.transferTo(newFile);
					} catch (IllegalStateException e) {
						// TODO 自动生成的 catch 块
						e.printStackTrace();
					} catch (IOException e) {
						// TODO 自动生成的 catch 块
						e.printStackTrace();
					}
					Avatar avatar=new Avatar();
					avatar.setId(id);
					avatar.setSize(size);
					avatar.setRealPath(path);
					avatar.setShowPath(showPath+saveName);
					avatar.setType(type);
					avatar.setCreateDate(new Date());
					int count=fileMapper.saveAvatarWhenRegister(avatar);
					if(count==1) {
						ids[i]=id;
					}else {
						if(newFile.exists()) {
							if(newFile.delete()) {
								System.out.println("############文件删除成功！");
							}
						}
					}
				}
			}
			return ids;
		}
	}

	@Override
	public Boolean deleteAvatarFiles(String ids) {
		int flag=0;
		if (ids==null||"".equals(ids)) {
			return false;
		}
		String[] idArr=null;
		if(ids.indexOf("|")!=-1) {
			idArr=ids.split("\\|");
		}else {
			idArr=new String[] {ids};
		}
		for(String id:idArr){
			//查头像信息
			Avatar hp=fileMapper.getAvatarById(id);
			String realPath=hp.getRealPath();
			if(hp!=null) {
				flag=fileMapper.deleteAvatarById(id);
			}
			if(!"".equals(realPath)&& realPath!=null) {
				File file = new File(realPath);
				if(file.exists()) {
					if(!file.delete()) {
						flag-=1;
					}
				}
			}
		}
		return flag==1?true:false;
	}

}
